﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LeakView.common;
using LeakView.service;

namespace LeakView.misc.view
{
    class FlowStatisticsGridView : DataGridView
    {
        private DataTable dataTable = new DataTable();

        public DataTable Table { get => dataTable; }

        public FlowStatisticsGridView()
        {

        }

        public void initialize()
        {
            this.AllowUserToResizeRows = false;
            this.AllowUserToResizeColumns = false;
            this.AllowUserToOrderColumns = false;
            this.AllowUserToAddRows = false;
            this.EditMode = DataGridViewEditMode.EditProgrammatically;
            this.DefaultCellStyle.SelectionBackColor = this.DefaultCellStyle.BackColor;
            this.DefaultCellStyle.SelectionForeColor = this.DefaultCellStyle.ForeColor;

            this.RowHeadersVisible = false;

            
            dataTable.Columns.Add("时间段");
            dataTable.Columns.Add("15分钟(m³)");
            dataTable.Columns.Add("30分钟(m³)");
            dataTable.Columns.Add("1小时(m³)");
            dataTable.Columns.Add("2小时(m³)");
            this.DataSource = dataTable;

            for (int i = 0; i < this.Columns.Count; i++)
            {
                this.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                this.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            }

            for (int i = 0; i < 96; i++)
            {
                dataTable.Rows.Add(getTimeStringByIndex(i), "", "", "", "");
            }
            this.DataSource = dataTable;

            this.ColumnHeadersDefaultCellStyle.Font = new Font("微软雅黑", 9, FontStyle.Regular);
            this.ColumnHeadersDefaultCellStyle.BackColor = Color.Gray;
            this.ColumnHeadersHeight = 32;
            this.RowsDefaultCellStyle.Font = new Font("微软雅黑", 9, FontStyle.Regular);

        }

        private string getTimeStringByIndex(int index)
        {
            int h = index / 4;
            int t = index % 4;

            switch(t)
            {
                case 0: return string.Format("{0:D2}:00-{0:D2}:15", h);
                case 1: return string.Format("{0:D2}:15-{0:D2}:30", h);
                case 2: return string.Format("{0:D2}:30-{0:D2}:45", h);
                case 3: return string.Format("{0:D2}:45-{1:D2}:00", h, h + 1);
                default: return "";
            }
        }

        public void setValues(List<AjaxMiscValue> values)
        {
            values.ForEach(v =>
            {
                this.setValue(v);
            });

            calculate30M();
            calculate60M();
            calculate120M();
        }

        private double getValue(int rowIndex)
        {
            try
            {
                string text = Table.Rows[rowIndex][1].ToString();
                if(text == null || text.Length == 0)
                {
                    return double.NaN;
                }
                else
                {
                    return double.Parse(text);
                }
            }
            catch
            {
                return double.NaN;
            }
        }

        private double getValue(int begin, int length)
        {
            double result = 0.0d;
            for (int i = begin; i < begin + length; i++)
            {
                result += getValue(i);
            }
            return result;
        }

        private string formatValue(double value)
        {
            if (double.IsNaN(value))
                return "";
            else
                return value.ToString();
        }

        private void calculate30M()
        {
            for(int i =0; i < (Rows.Count); i+=2)
            {
                var v = formatValue(getValue(i, 2));
                Table.Rows[i + 0][2] = v;
                Table.Rows[i + 1][2] = v;
            }
        }

        private void calculate60M()
        {
            for (int i = 0; i < (Rows.Count); i += 4)
            {
                var v = formatValue(getValue(i, 4));
                Table.Rows[i + 0][3] = v;
                Table.Rows[i + 1][3] = v;
                Table.Rows[i + 2][3] = v;
                Table.Rows[i + 3][3] = v;
            }
        }

        private void calculate120M()
        {
            for (int i = 0; i < (Rows.Count); i += 8)
            {
                var v = formatValue(getValue(i, 8));

                Table.Rows[i + 0][4] = v;
                Table.Rows[i + 1][4] = v;
                Table.Rows[i + 2][4] = v;
                Table.Rows[i + 3][4] = v;
                Table.Rows[i + 4][4] = v;
                Table.Rows[i + 5][4] = v;
                Table.Rows[i + 6][4] = v;
                Table.Rows[i + 7][4] = v;
            }
        }

        public void setValue(AjaxMiscValue value)
        {
            setValue(value.birth, value.value);
        }

        public void setValue(long timestamp, double value)
        {
            DateTime dt = Tools.ConvertLongToDateTime(timestamp);
            DateTime dtToday = new DateTime(dt.Year, dt.Month, dt.Day);
            TimeSpan ts = dt - dtToday;
            
            int rowIndex = (int)ts.TotalMilliseconds / 900000;

            if (double.IsNaN(value))
                Table.Rows[rowIndex][1] = "";
            else
                Table.Rows[rowIndex][1] = value;

            Console.WriteLine(dt.ToString("HH:mm:ss") + "-------->" + getTimeStringByIndex(rowIndex));

        }

        public void clearValues()
        {
            for(int i = 0; i < this.RowCount; i ++)
            {
                Table.Rows[i][1] = "";
                Table.Rows[i][2] = "";
                Table.Rows[i][3] = "";
                Table.Rows[i][4] = "";
            }
        }

        public void updateData()
        {
            this.DataSource = dataTable;
        }

        protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
        {
            try
            {
                if (e.RowIndex > -1 && e.ColumnIndex > -1)
                {
                    DrawCell(e);
                }
                base.OnCellPainting(e);
            } catch { }
        }

        #region 自定义方法
        /// <summary>
        /// 画单元格
        /// </summary>
        /// <param name="e"></param>
        private void DrawCell(DataGridViewCellPaintingEventArgs e)
        {
            if (e.CellStyle.Alignment == DataGridViewContentAlignment.NotSet)
            {
                e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            }

            Brush gridBrush = new SolidBrush(this.GridColor);
            SolidBrush backBrush = new SolidBrush(e.CellStyle.BackColor);
            SolidBrush fontBrush = new SolidBrush(e.CellStyle.ForeColor);
            int cellwidth;
            //上面相同的行数
            int UpRows = 0;
            //下面相同的行数
            int DownRows = 0;
            //总行数
            int count = 0;

            if(e.ColumnIndex == 2)
            {
                count = 2;
                int of = e.RowIndex % 2;
                UpRows = of + 1;
                DownRows = count - of;
            }
            else if(e.ColumnIndex == 3)
            {
                count = 4;
                int of = e.RowIndex % 4;
                UpRows = of + 1;
                DownRows = count - of;
            }
            else if (e.ColumnIndex == 4)
            {
                count = 8;
                int of = e.RowIndex % 8;
                UpRows = of + 1;
                DownRows = count - of;
            }
            else
            {
                return;
            }

            cellwidth = e.CellBounds.Width;
            Pen gridLinePen = new Pen(gridBrush);
            //string curValue = e.Value == null ? "" : e.Value.ToString().Trim();
            //string curSelected = this.CurrentRow.Cells[e.ColumnIndex].Value == null ? "" : this.CurrentRow.Cells[e.ColumnIndex].Value.ToString().Trim();

            if (this.Rows[e.RowIndex].Selected)
            {
                backBrush.Color = e.CellStyle.SelectionBackColor;
                fontBrush.Color = e.CellStyle.SelectionForeColor;
            }
            
            //以背景色填充
            e.Graphics.FillRectangle(backBrush, e.CellBounds);

            //画字符串
            PaintingFont(e, cellwidth, UpRows, DownRows, count);

            //画底边
            if (DownRows == 1)
            {
                e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
                count = 0;
            }

            // 画右边线
            e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);

            e.Handled = true;

        }
        /// <summary>
        /// 画字符串
        /// </summary>
        /// <param name="e"></param>
        /// <param name="cellwidth"></param>
        /// <param name="UpRows"></param>
        /// <param name="DownRows"></param>
        /// <param name="count"></param>
        private void PaintingFont(System.Windows.Forms.DataGridViewCellPaintingEventArgs e, int cellwidth, int UpRows, int DownRows, int count)
        {
            SolidBrush fontBrush = new SolidBrush(e.CellStyle.ForeColor);
            int fontheight = (int)e.Graphics.MeasureString(e.Value.ToString(), e.CellStyle.Font).Height;
            int fontwidth = (int)e.Graphics.MeasureString(e.Value.ToString(), e.CellStyle.Font).Width;
            int cellheight = e.CellBounds.Height;

            if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomCenter)
            {
                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y + cellheight * DownRows - fontheight);
            }
            else if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomLeft)
            {
                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y + cellheight * DownRows - fontheight);
            }
            else if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomRight)
            {
                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y + cellheight * DownRows - fontheight);
            }
            else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleCenter)
            {
                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
            }
            else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleLeft)
            {
                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
            }
            else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleRight)
            {
                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
            }
            else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopCenter)
            {
                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1));
            }
            else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopLeft)
            {
                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y - cellheight * (UpRows - 1));
            }
            else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopRight)
            {
                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y - cellheight * (UpRows - 1));
            }
            else
            {
                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
            }
        }
        #endregion
    }



}
